package com.bt7274.service.impl;

import com.bt7274.mapper.*;
import com.bt7274.pojo.*;
import com.bt7274.pojo.bo.CommentBO;
import com.bt7274.pojo.bo.PostBO;
import com.bt7274.pojo.vo.CommentVO;
import com.bt7274.pojo.vo.PostDetailVO;
import com.bt7274.pojo.vo.PostVO;
import com.bt7274.pojo.vo.UserVO;
import com.bt7274.service.CommentService;
import com.bt7274.service.PostService;
import com.bt7274.utils.SensitiveWordUtil;
import com.bt7274.utils.SessionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @Data 2025/3/25 02:17
 * @Author hp
 * @Version 1.0
 * @Description UserServiceImpl
 */
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PostMapper postMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private NotificationMapper notificationMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private SensitiveWordUtil sensitiveWordUtil;

    @Override
    public void addComment(CommentBO commentBO) {
        Post post=postMapper.selectPostById(commentBO.getPostId());
        if(post==null){
            throw new RuntimeException("帖子不存在");
        }
        if(post.getStatus()==3){
            throw new RuntimeException("帖子已锁定，无法回复");
        }
        // 敏感词检测逻辑
        boolean containsSensitive = sensitiveWordUtil.isContaintSensitiveWord(
                post.getTitle() + post.getContent(),2
        );
        if(containsSensitive){
            throw new RuntimeException("帖子中有敏感内容，发布失败");
        }

        Comment comment = new Comment();
        BeanUtils.copyProperties(commentBO, comment);
        String userId= SessionUtils.getCurrentUserId();
        // 设置当前登录用户 ID（此处先写死）
        comment.setUserId(userId); //
        System.out.println(comment.getReplyToCommentId()+"====="+comment.getReplyToUserId());
        // 设置时间
        comment.setCreatedTime(LocalDateTime.now());
        // 楼层号自增
        String redisKey = "comment:floor:" + commentBO.getPostId();
        //redisTemplate.opsForValue().increment("post:comment_count:" + commentBO.getPostId());
        postMapper.incrementReplyCount(post.getId());//TODO: 这里需要加锁，防止多线程下的并发问题
        postMapper.updatePostUpdatedTime(post.getId());
        Long floor = redisTemplate.opsForValue().increment(redisKey);
        if (floor != null) {
            comment.setFloorNumber(floor.intValue());
        }

        // 插入数据库
        commentMapper.insertComment(comment);
        Notification notification = new Notification();
        notification.setPostId(comment.getPostId());
        if(commentBO.getReplyToCommentId()==null){
            notification.setReceiverId(String.valueOf(post.getUserId()));
            notification.setContent("你的帖子\""+post.getTitle()+"\"有新的评论");
            notification.setType("reply_post");
        }
        else{
            notification.setReceiverId(commentBO.getReplyToUserId());
            notification.setCommentId(comment.getId());
            notification.setContent("你在帖子\""+post.getTitle()+"\"的评论\""+"\"有新的回复");
            notification.setType("reply_comment");
        }
        notification.setSenderId(userId);
        notification.setCreatedTime(LocalDateTime.now());
        notificationMapper.insertNotification(notification);
    }

    // 删除评论
    @Override
    public void deleteCommentById(String commentId) {
        Comment comment = commentMapper.selectCommentById(commentId);
        Post post=postMapper.selectPostById(comment.getPostId());
        if(post==null){
            throw new RuntimeException("帖子不存在");
        }
        postMapper.decrementReplyCount(post.getId());
        commentMapper.deleteCommentById(commentId);
    }

    // 获取指定帖子的评论列表
    @Override
    public List<CommentVO> getCommentsByPostId(String postId, int page, int pageSize) {
        int offset = (page - 1) * pageSize;
        List<Comment> commentList = commentMapper.selectCommentsByPostId(postId, offset, pageSize);

        List<CommentVO> voList = new ArrayList<>();
        for (Comment c : commentList) {
            CommentVO vo = new CommentVO();
            BeanUtils.copyProperties(c, vo);

            // 评论人信息
            User user = userMapper.selectUserById(c.getUserId());
            if (user != null) {
                UserVO userVO = new UserVO();
                Permission permission=permissionMapper.selectById(user.getPermissionGroup());
                BeanUtils.copyProperties(user, userVO);
                userVO.setLevel(permission.getName());
                vo.setUser(userVO);
            }
            // 回复相关信息（楼层号、用户名）
            if (c.getReplyToCommentId() !=null) {
                Comment replyComment = commentMapper.selectCommentById(c.getReplyToCommentId());
                //System.out.println(replyComment.getContent()+"===="+replyComment.getFloorNumber());
                if (replyComment != null) {
                    vo.setReplyToFloorNumber(replyComment.getFloorNumber());
                    vo.setReplYToContent(replyComment.getContent());
                    User replyUser = userMapper.selectUserById(replyComment.getUserId());
                    if (replyUser != null) {
                        vo.setReplyToUsername(replyUser.getUsername());
                        vo.setReplyToUserId(replyUser.getId());
                    }
                }
            }

            voList.add(vo);
        }

        return voList;
    }
}
